<template>
  <div class="page">
    <s-header name="开工申请办理" :back="'/government/start-work'"></s-header>
    <div class="card-box">
      <!-- <div class="header-title">建房申请单号：{{ applyForm.applyOrderNo }}</div> -->
      <div class="header-title title-message">
        <div class="title-left">开工申请信息</div>
        <div class="title-right" @click="toBuildApply">建房申请详情</div>
      </div>
      <van-divider />
      <div class="content">
        <van-cell-group>
          <van-cell title="申请单号" :value="applyForm.applyOrderNo" :border="false" />
          <van-cell title="申请人" :value="applyForm.applyName" :border="false" />
          <!-- <van-cell
            title="申请时间"
            :value="applyForm.applyTime"
            :border="false"
          /> -->
          <van-cell title="联系电话" :value="applyForm.applyPhone" :border="false" />
          <!-- <van-cell
            title="申请理由"
            :value="applyForm.applyReasonsDesc"
            :border="false"
          />
          <van-cell
            title="建房类型"
            :value="applyForm.buildTypeName"
            :border="false"
          />
          <van-cell
            title="家庭住址"
            :value="applyForm.applyHouseAddress"
            :border="false"
          /> -->
          <van-cell title="申请内容" :value="recordForm.applyContent" :border="false" />
          <van-cell title="现场图片" />
          <van-cell>
            <div class="item-list">
              <div v-for="file in recordForm.photos" :key="file.id" style="margin-right: 10px" @click="handleReview(file.url)">
                <van-image width="55" height="55" :src="`${fileServerPrefix}${file.url}`" />
              </div>
            </div>
          </van-cell>
          <van-cell title="相关材料" />
          <van-cell>
            <div v-for="file in recordForm.files" :key="file.id" class="item-list">
              <div class="item-image">
                <van-image width="15" height="15" :src="imgSrc" />
              </div>
              <div class="item-name" @click="handleDownload(file.url, file.suffix)">
                {{ file.name }}
              </div>
              <div class="item-size">({{ converSize(file.size) }})</div>
            </div>
          </van-cell>
          <van-cell title="其他相关材料" />
          <van-cell>
            <div v-for="file in recordForm.others" :key="file.id" class="item-list">
              <div class="item-image">
                <van-image width="15" height="15" :src="imgSrc" />
              </div>
              <div class="item-name" @click="handleDownload(file.url, file.suffix)">
                {{ file.name }}
              </div>
              <div class="item-size">({{ converSize(file.size) }})</div>
            </div>
          </van-cell>
        </van-cell-group>
      </div>
    </div>
    <!-- <div class="card-box">
      <div class="header-title">现场图片</div>
      <van-divider />
      <div class="item-list">
        <div
          v-for="file in recordForm.photos"
          :key="file.id"
          style="margin-right: 10px"
          @click="handleReview(file.url)"
        >
          <van-image
            width="55"
            height="55"
            :src="`${fileServerPrefix}${file.url}`"
          />
        </div>
      </div>
    </div> -->
    <!-- <div class="card-box">
      <div class="header-title">相关材料</div>
      <van-divider />
      <div v-for="file in recordForm.others" :key="file.id" class="item-list">
        <div class="item-image">
          <van-image width="15" height="15" :src="imgSrc" />
        </div>
        <div class="item-name" @click="handleDownload(file.url, file.suffix)">
          {{ file.name }}
        </div>
        <div class="item-size">
          ({{ `${(file.size / (1024 * 1024)).toFixed(2)}` }}MB)
        </div>
      </div>
    </div> -->
    <van-form @submit="onSubmit">
      <div class="card-box">
        <div class="header-title">开工查验</div>
        <van-divider />
        <div class="content">
          <van-cell-group>
            <van-field
              v-model="saveForm.checkTime"
              is-link
              readonly
              name="calendar"
              label="巡查日期"
              required
              placeholder="点击选择日期"
              @click="showCalendar = true"
              :rules="[{ required: true, message: '请选择巡查日期' }]"
            />
            <van-calendar v-model:show="showCalendar" @confirm="onConfirm" />
            <van-field
              v-model="saveForm.presentDept"
              name="到场部门"
              label="到场部门"
              required
              placeholder="请输入到场部门"
              :rules="[{ required: true, message: '请填写到场部门' }]"
            />
            <van-field
              v-model="saveForm.presentPerson"
              required
              name="到场人员"
              label="到场人员"
              placeholder="请输入到场人员"
              :rules="[{ required: true, message: '请填写到场人员' }]"
            />
            <van-field
              v-model="saveForm.checkContet"
              rows="3"
              autosize
              type="textarea"
              required
              maxlength="300"
              show-word-limit
              name="检查内容"
              label="检查内容"
              placeholder="请输入检查内容"
              :rules="[{ required: true, message: '请填写检查内容' }]"
            />
          </van-cell-group>
        </div>
      </div>
      <div class="card-box">
        <div class="header-title title-required">相关材料</div>
        <van-divider />
        <div class="item-list">
          <image-upload v-model:value="fileList" fileType="A22" @uploadBack="uploadBack"></image-upload>
        </div>
      </div>
      <div class="card-box">
        <div class="header-title title-required">现场图片</div>
        <van-divider />
        <div class="item-list">
          <image-upload v-model:value="photoList" fileType="A21" @uploadBack="uploadBack"></image-upload>
        </div>
      </div>
      <div class="card-box">
        <div class="header-title title-required">开工审批</div>
        <van-divider />
        <div class="item-list">
          <van-radio-group
            v-model="saveForm.applyStatus"
            :rules="[{ required: true, message: '请选择开工审批', trigger: 'onChange' }]"
            direction="horizontal"
          >
            <van-radio name="22">同意开工</van-radio>
            <van-radio name="23">不同意开工</van-radio>
            <van-radio name="99">挂起</van-radio>
          </van-radio-group>
        </div>
      </div>
      <div class="card-box">
        <div class="header-title title-required">办理意见</div>
        <van-divider />
        <div class="content">
          <van-field
            v-model="saveForm.handleOpinions"
            class="noPadding"
            label=""
            rows="3"
            autosize
            type="textarea"
            placeholder="请输入办理意见"
            :rules="[{ required: true, message: '请输入办理意见' }]"
          />
        </div>
      </div>
      <div class="btn-group">
        <van-button type="button" :loading="btnLoading" class="cus-btn btn-default" @click="handleSave()">保存</van-button>
        <van-button type="button" class="cus-btn btn-success" :loading="btnLoading" native-type="submit">提交</van-button>
        <!-- @click="handleSave(1)" -->
      </div>
    </van-form>
  </div>
</template>

<script>
import { reactive, onMounted, toRefs, computed, getCurrentInstance } from 'vue'
import { useStore } from 'vuex'
import sHeader from '@/components/SimpleHeader'
import { useRoute, useRouter } from 'vue-router'
import imgSrc from '@/assets/Images/file-icon.png'
import { ImagePreview, Toast } from 'vant'
import ImageUpload from '@/components/ImageUpload'
import { getLoitBuildStartApplySelectBuild, savewsLoitBuildHandleApply } from '@/service/start-apply'
export default {
  components: {
    sHeader,
    ImageUpload,
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    const state = reactive({
      btnLoading: false,
      applyBaseId: '',
      idParams: '',
      imgSrc: imgSrc,
      showCalendar: false,
      startId: '',
      applyForm: {
        applyOrderNo: '',
        applyName: '',
        applyTime: '',
        applyPhone: '',
        applyReasonsDesc: '',
        buildTypeName: '',
        applyContent: '',
        applyHouseAddress: '',
      },
      recordForm: {
        photos: [],
        files: [],
        others: [],
        applyContent: '',
      },
      saveForm: {
        checkTime: '',
        presentDept: '',
        presentPerson: '',
        checkContet: '',
        applyStatus: '22',
        handleOpinions: '',
      },
      // 上传图片
      fileList: [],
      photoList: [],
      attachInfoDTOList: [],
      // attachInfoPhotoList: [],
      // attachInfoOtherList: [],
    })

    // 全局属性
    const { listAssign } = getCurrentInstance().appContext.config.globalProperties

    onMounted(() => {
      state.idParams = route.query.id
      state.applyBaseId = route.query.applyBaseId
      getLoitBuildStartApplySelectBuild(state.applyBaseId).then((res) => {
        if (res.success) {
          state.applyForm = {
            ...res.body.obj.buildApplyBase,
          }
          const loitBuild = res.body.obj.loitBuildStartApply
          if (loitBuild) {
            listAssign(state.recordForm, loitBuild)
          }
          const applyHandle = res.body.obj.loitBuildStartApplyHandle
          state.startId = applyHandle.id
          if (applyHandle) {
            const saveList = {
              checkTime: applyHandle.checkTime,
              presentDept: applyHandle.presentDept,
              presentPerson: applyHandle.presentPerson,
              checkContet: applyHandle.checkContet,
              applyStatus: applyHandle.reviewResult ? applyHandle.reviewResult : '22',
              handleOpinions: applyHandle.handleOpinions,
            }
            state.saveForm = saveList
            // state.saveForm.applyStatus = state.saveForm.reviewResult;
            const checkTime = state.saveForm.checkTime
            if (checkTime) {
              state.saveForm.checkTime = checkTime.substring(0, 10)
            }
            // if (applyHandle.files && applyHandle.files.length > 0) {
            //   state.fileList = applyHandle.files
            //   state.fileList.forEach((res) => {
            //     res.url = fileServerPrefix.value + res.url
            //   })
            // }
            // if (applyHandle.photos && applyHandle.photos.length > 0) {
            //   state.photoList = applyHandle.photos
            //   state.photoList.forEach((res) => {
            //     res.url = fileServerPrefix.value + res.url
            //   })
            // }

            let files = applyHandle.files
            let photos = applyHandle.photos
            if (files && files.length > 0) {
              files.forEach((item) => {
                if (item.url.indexOf(fileServerPrefix.value) === -1) {
                  item.filePath = item.url
                  item.url = fileServerPrefix.value + item.url
                }
              })
            }
            if (photos && photos.length > 0) {
              photos.forEach((item) => {
                if (item.url.indexOf(fileServerPrefix.value) === -1) {
                  item.filePath = item.url
                  item.url = fileServerPrefix.value + item.url
                }
              })
            }
            state.fileList = files
            state.photoList = photos
            // state.attachInfoDTOList = applyHandle.photos.concat(applyHandle.files)
          }
        }
      })
    })
    // 保存节点
    const saveNode = () => {
      state.nodeShow = false
    }
    // 取消保存节点
    const cancelNode = () => {
      state.nodeShow = false
    }

    //  选择日期
    const formatDate = (date) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    const onConfirm = (date) => {
      state.saveForm.checkTime = formatDate(date)
      state.showCalendar = false
    }

    // 查看图片材料
    store.dispatch('getFileServerPrefix')
    const handleReview = (url) => {
      const imgUrl = fileServerPrefix.value + url
      ImagePreview({
        images: [imgUrl],
        showIndex: true,
        showIndicators: true,
        closeable: true,
      })
    }

    const handleDownload = (url, suffix) => {
      const imgUrl = fileServerPrefix.value + url
      if (suffix === 'png' || suffix === 'jpg' || suffix === 'jpeg') {
        ImagePreview({
          images: [imgUrl],
          showIndex: true,
          showIndicators: true,
          closeable: true,
        })
      } else if (suffix === 'pdf') {
        window.open(url)
      } else {
        let a = document.createElement('a')
        a.href = imgUrl
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      }
    }
    const fileServerPrefix = computed(() => {
      return store.state.fileServerPrefix
    })

    // 文件上传后回调
    const uploadBack = (fileList, type) => {
      if (type === 'A21') {
        state.photoList = fileList
      } else if (type === 'A22') {
        state.fileList = fileList
      }
    }

    const handSendData = (isSubmit) => {
      return new Promise((resove, reject) => {
        let fileList = JSON.parse(JSON.stringify(state.fileList))
        let photoList = JSON.parse(JSON.stringify(state.photoList))
        fileList.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })
        photoList.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })

        let params = {
          ...state.saveForm,
          id: state.startId,
          startApplyId: state.idParams,
          applyBaseId: state.applyBaseId,
          attachInfoDTOList: [...photoList, ...fileList],
          isSubmit: isSubmit,
        }
        state.btnLoading = true
        savewsLoitBuildHandleApply(params)
          .then((res) => {
            if (res.code == 100) {
              resove(true)
            }
            state.btnLoading = false
          })
          .catch((err) => {
            state.btnLoading = false
            reject(err)
          })
      })
    }

    // 保存
    const handleSave = () => {
      handSendData(0).then(() => {
        Toast.success('保存成功')
        setTimeout(() => {
          router.push({ path: '/government/start-work' })
        }, 500)
      })
    }
    // 提交
    const onSubmit = () => {
      if (state.photoList.length === 0) {
        Toast.fail(`请上传现场图片`)
        return
      }
      if (state.fileList.length === 0) {
        Toast.fail(`请上传相关材料`)
        return
      }

      handSendData(1).then(() => {
        Toast.success('提交成功')
        setTimeout(() => {
          router.push({ path: '/government/start-work' })
        }, 500)
      })
    }
    // 跳转建房详情
    const toBuildApply = () => {
      router.push({
        path: `/government/build-apply/detail/${state.applyBaseId}`,
      })
    }
    return {
      fileServerPrefix,
      ...toRefs(state),
      cancelNode,
      saveNode,
      handleReview,
      handleDownload,
      onConfirm,
      handleSave,
      toBuildApply,
      onSubmit,
      uploadBack,
    }
  },
}
</script>

<style lang="less" scoped>
@import '@/common/style/mixin';
.page {
  color: #2e3f6a;
  font-family: Microsoft YaHei;
  font-weight: 400;
  .card-box {
    margin-top: 16px;
    padding: 4px;
    background: #ffffff;
    border-radius: 10px;
    .header-title {
      padding: 16px 0 0 16px;
      font-size: 16px;
      font-weight: bold;
      .title-left {
        font-size: 16px;
        font-weight: bold;
      }
      .title-right {
        font-size: 14px;
        padding: 8px 10px;
        margin-right: 16px;
        background: #3487f6;
        color: #ffffff;
        border-radius: 8px;
      }
    }
    .title-message {
      display: flex;
      justify-content: space-between;
    }
    .header-right {
      padding-right: 10px;
      font-size: 14px;
      color: #3487f6;
    }
    /deep/.van-cell__title {
      font-size: 16px;
      color: #9297ae;
    }
    /deep/.van-cell__value {
      font-size: 16px;
      color: #2e3f6a;
    }
    .card-list {
      display: flex;
      padding: 10px;
      overflow-x: auto;
    }
    .item-list {
      padding: 10px 16px;
      display: flex;
      .item-image {
        margin-right: 5px;
      }
      .item-name {
        margin-right: 5px;
        font-size: 14px;
        font-weight: 400;
        color: #3487f6;
      }
      .item-size {
        font-size: 14px;
        font-weight: 400;
        color: #9297ae;
      }
    }
    .card-item {
      padding: 15px;
      margin-right: 10px;
      text-align: center;
      word-wrap: break-word;
      color: #2e3f6a;
      font-size: 14px;
      background: #f4f5f9;
      border-radius: 10px;
      //   flex-basis: 50px;
      flex-shrink: 0;
      white-space: nowrap;
    }
    .select-item {
      background: #3487f6;
      color: #ffffff;
    }
    /*箭头向下*/
    .arrow-down {
      position: absolute;
      top: 42px;
      border-left: 8px solid transparent;
      border-right: 8px solid transparent;
      border-top: 8px solid #0066cc;
    }
  }
  .record-btn {
    margin: 12px 14px;
    padding: 10px 20px;
    text-align: center;
    background: #ffffff;
    border: 2px solid #c7cad8;
    border-radius: 20px;
    font-size: 16px;
    line-height: 20px;
  }
  .history-record {
    margin: 16px;
    .record-title {
      font-size: 16px;
      margin: 5px 0;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #2e3f6a;
    }
    .record-item {
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
      background: #f4f5f9;
      border-radius: 6px;
      width: 100%;
      padding: 15px 5px;
    }
    .item-date {
      font-size: 13px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #9297ae;
      margin-right: 10px;
    }
    .item-content {
      font-size: 15px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #2e3f6a;
      margin-right: 10px;
    }
    .item-icon {
      padding-top: 2px;
      font-size: 16px;
      color: #2e3f6a;
    }
  }
  .content {
    padding: 0 16px;
    padding-bottom: 16px;
    // font-size: 15px;
    // font-weight: 400;
    // line-height: 25px;
    // color: #2e3f6a;
  }
  .btn-group {
    padding: 20px 0;
    display: flex;
    .cus-btn {
      font-size: 16px;
      width: 100%;
    }
  }
}
.title-required::before {
  margin-right: 5px;
  color: var(--van-field-required-mark-color);
  content: '*';
}
</style>